package doubleLinkedList

import (
	"fmt"
)

// 实现功能

//双向链表的数据结构

type Object interface{}

type Node struct {
	Data Object
	pre  *Node
	next *Node
}

type DoubleList struct {
	headNode *Node
}

//判断链表是否为空
func (this *DoubleList) Empty() bool {
	if this.headNode == nil {
		return true
	} else {
		return false
	}
}

//尾部添加元素
func (this *DoubleList) Add(data Object) {
	node := &Node{Data: data}
	cur := this.headNode
	if cur == nil {
		this.headNode = node
	} else {
		for cur.next != nil {
			cur = cur.next
		}
		node.pre = cur
		cur.next = node
	}
}

//链表长度
func (this *DoubleList) Length() int {
	count := 0
	cur := this.headNode
	if cur != nil {
		for cur != nil {
			cur = cur.next
			count++
		}
	}
	return count
}

//从前向后展示链表
func (this *DoubleList) ShowList() {
	cur := this.headNode
	for cur != nil {
		fmt.Printf("\t %v", cur.Data)
		cur = cur.next
	}
	fmt.Println()
}

//从后向前展示
func (this *DoubleList) ShowListFromTail() {
	tail := this.headNode
	for tail.next != nil {
		tail = tail.next
	}

	for tail != nil {
		fmt.Printf("\t %v", tail.Data)
		tail = tail.pre
	}
}

// 移除元素
func (this *DoubleList) RemoveNode(data Object) {
	cur := this.headNode
	if cur.Data == data {
		// 移除头元素
		new_head := cur.next
		new_head.pre = nil
		this.headNode = new_head
	} else {
		for cur != nil {
			if cur.Data == data {
				// 移除元素
				pre := cur.pre
				next := cur.next

				//当前节点被跳过, 会被当做垃圾回收掉
				next.pre = pre
				pre.next = next
			}
			cur = cur.next
		}
	}
}
